package com.xbongbong.paas.business.rule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2020/10/14 11:08
 */
@Component
public class BaseBusinessRuleHelp {
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    public Map<Long, JSONObject> getSubDataMap(String corpid, Integer saasMark, Integer businessType, Long formId, Set<Long> parentIdList, Integer page, Integer pageSize, Integer del) throws XbbException {
        Map<Long, JSONObject> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isEmpty(parentIdList)) {
            return formDataMap;
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, del);
        param.put("dataIdIn", parentIdList);
        param.put(StringConstant.FORM_ID, formId);
        IndexTypeEnum indexTypeEnum = IndexTypeEnum.getSubEnum(EsHelper.getIndexTypeEnum(saasMark, businessType));
        List<? extends  PaasFormSubDataEntity> formSubDataList = paasFormSubDataModel.getSubDataList(param, indexTypeEnum);
        if (CollectionsUtil.isNotEmpty(formSubDataList)) {
            formSubDataList.forEach(item->{
                JSONObject jsonObject = new JSONObject();
                if (formDataMap.containsKey(item.getDataId())) {
                    jsonObject = formDataMap.get(item.getDataId());
                }
                if (jsonObject.containsKey(item.getAttr())) {
                    JSONArray jsonArray = jsonObject.getJSONArray(item.getAttr());
                    jsonArray.add(item.getData());
                    jsonObject.put(item.getAttr(), jsonArray);
                } else {
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.add(item.getData());
                    jsonObject.put(item.getAttr(), jsonArray);
                }
                formDataMap.put(item.getDataId(), jsonObject);
            });
        }
        return formDataMap;
    }
}
